package models

import (
	"cmdb/errors"
	"cmdb/forms"
	"cmdb/utils"
	"fmt"
	"github.com/astaxie/beego/orm"
)

type User struct {
	ID       int    `orm:"column(id)"`
	Num      int    `orm:"column(num)"`
	Name     string `orm:"column(name)"`
	PassWord string `orm:"column(password)"`
	Sex      int    `orm:"column(sex)"`
	Status   int    `orm:"column(status)"`
	Vocation string `orm:"column(vocation)"`
	Salary   string `orm:"column(salary)"`
	UserName string `orm:"column(username)"`
}

func GetUser(username string) *User {
	ormer := orm.NewOrm() //创建Orm对象
	user := &User{UserName: username}
	err := ormer.Read(user, "username")
	if err != nil {
		fmt.Println(err)
		return nil
	} else {
		return user
	}
}

func IdGetUser(Id int) *User {
	ormer := orm.NewOrm()
	user := &User{ID: Id}
	if err := ormer.Read(user, "id"); err != nil {
		fmt.Println(err)
		return nil
	} else {
		return user
	}
}

func (u *User) ValidPassword(password string) bool {
	fmt.Println("用户旧密码", u)
	return utils.HashPJ(u.PassWord, password) //判断密码是否相同
}

func (u *User) QueryUser(q string) []*User {
	ormer := orm.NewOrm()
	queryset := ormer.QueryTable(&User{}) //得到表格对象
	cond := orm.NewCondition()            //创建一个condition对象
	var users []*User
	if q != "" {
		cond = cond.Or("num__iexact", q).Or("name__iexact", q)
		queryset.SetCond(cond).All(&users)
	} else {
		queryset.All(&users)
	}

	return users
}

func (u *User) SexText() string {
	if u.Sex == 1 {
		return "男"
	} else {
		return "女"
	}
}

func (u *User) StatusText() string {
	switch u.Status {
	case 0:
		return "离职"
	case 1:
		return "在职"
	case 2:
		return "未知"
	}
	return "未知错误选项"
}

func (u *User) Modify() {

}

func (u *User) ModifyUser(form *forms.Modify) *errors.Errors {
	err := errors.New()
	if form.OldPassword == form.PassWord {
		err.Add("default", "新旧密码不能相同")
	} else if form.PassWord != form.NewPassWord {
		err.Add("default", "两次密码输入不一致")
	} else if len(form.PassWord) < 4 || len(form.PassWord) > 12 {
		err.Add("default", "用户的密码长度不正确")
	} else if u.ValidPassword(form.OldPassword) != true {
		err.Add("default", "用户旧密码输入错误")
	} else {
		ormer := orm.NewOrm()
		user := &User{
			ID: form.ID,
		}
		ormer.Read(user)
		user.PassWord = utils.HashAdd(form.PassWord) //设置新密码
		ormer.Update(user)                           //修改新密码
	}
	return err
}
